package com.lbb.waimai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lbb.waimai.entiry.Category;
import com.lbb.waimai.entiry.ShoppingCart;
import com.lbb.waimai.entiry.vo.ShoppingCartVo;
import com.lbb.waimai.mapper.CategoryMapper;
import com.lbb.waimai.mapper.ShoppingCartMapper;
import com.lbb.waimai.service.CategoryService;
import com.lbb.waimai.service.ShoppingCartService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {
    //获取购物车的内容,根据userid以及status为0（未生成订单，未支付）状态下的购物车
    @Override
    public List<ShoppingCart> findInCart(Long userId) {
        QueryWrapper<ShoppingCart> wrapper = new QueryWrapper<>();
        wrapper.eq("u_id",userId);
        List<ShoppingCart> cartList = baseMapper.selectList(wrapper);
        return cartList;
    }

    //清空购物车,删除购物车中状态为0的食品
    @Override
    public void clearCart(Integer userId) {
        QueryWrapper<ShoppingCart> wrapper = new QueryWrapper<>();
        wrapper.eq("u_id",userId);
        baseMapper.delete(wrapper);
    }

    //根据菜品id删除菜品
    @Override
    public void deleteFood(Integer id, Integer userId) {
        QueryWrapper<ShoppingCart> wrapper = new QueryWrapper<>();
        wrapper.eq("u_id",userId);
        wrapper.eq("f_id",id);
        baseMapper.delete(wrapper);
    }

    //加入购物车，要判断是要更新数量还是新增
    @Override
    public void takeInCart(ShoppingCartVo shoppingCartVo, Integer userId) {
        ShoppingCart shoppingCart = new ShoppingCart();
        Integer fid = shoppingCartVo.getId();
        //如果根据菜品id和用户id查出来数据库已经含有该菜品，就更新数量
        QueryWrapper<ShoppingCart> wrapper = new QueryWrapper<>();
        wrapper.eq("f_id",fid);
        wrapper.eq("u_id",userId);
        ShoppingCart cart = baseMapper.selectOne(wrapper);
        double sum=0;
        if(cart != null){
            //更新
            cart.setFCount(shoppingCartVo.getCount());
            sum = shoppingCartVo.getCount() * cart.getFPrice();
            cart.setFSum(sum);
            baseMapper.updateById(cart);
            return;
        }
        shoppingCart.setFName(shoppingCartVo.getName());
        shoppingCart.setFCount(shoppingCartVo.getCount());
        shoppingCart.setFId(fid);
        shoppingCart.setFPrice(shoppingCartVo.getPrice());
        shoppingCart.setUId(userId);
        sum = shoppingCart.getFCount() * shoppingCart.getFPrice();
        shoppingCart.setFSum(sum);
        baseMapper.insert(shoppingCart);
    }
}
